<template>
    <el-dialog title="员工导入" :visible="visible" width="35%" :before-close="beforeClose">
        <el-upload
                ref="uploadxls"
                :limit="1"
                :action="importEmployeeXlsApi"
                :auto-upload="false"
                :before-upload="beforeXlsUpload"
                :data="uploadData"
                :on-success="successUpload"
        >
            <el-button slot="trigger" type="primary">选取文件</el-button>
            <div slot="tip">只能上传xls文件，且不超过1M</div>
        </el-upload>
        <div class="dialog-footer" slot="footer">
            <el-button type="primary" @click="submitUpload()">上传</el-button>
            <el-button @click="beforeClose()">取消</el-button>
        </div>
    </el-dialog>
</template>

<script>
    import {
        importEmployeeXlsApi
    } from '@/request/api'

    export default {
        name: "UploadDialog",
        props: {
            visible: {
                type: Boolean,
                default: false
            }
        },
        data() {
            return {
                importEmployeeXlsApi: importEmployeeXlsApi,
                uploadData: {
                    token: localStorage.getItem('token')
                }

            }
        },
        methods: {
            beforeClose() {
                this.$emit('closeDialog')
            },
            beforeXlsUpload(file) {
                const isXls = file.name.indexOf('.xls') > -1
                const isLt1M = file.size / 1024 / 1024 < 1;

                if (!isXls) {
                    this.$message.error('上传的文件格式为xls或xlsx')
                }
                if (!isLt1M) {
                    this.$message.error('上传的文件大小不能超过2M')
                }
                return isXls && isLt1M
            },
            successUpload(res, file) {
                console.log(res)
                if (res.success === true) {
                    this.$message.success('导入文件成功')
                } else {
                    this.$message.error(res.msg || '导入文件失败')
                }
            },
            submitUpload() {
                this.$refs['uploadxls'].submit()
            }
        }
    }
</script>

<style scoped>

</style>